<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>登录账号</h2>
          <p class="subtitle">欢迎回来，请登录您的账号</p>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="account">
          <el-input
            v-model="form.account"
            :placeholder="accountPlaceholder"
            prefix-icon="User"
          >
            <template #append>
              <el-select
                v-model="loginType"
                style="width: 100px"
                @change="handleLoginTypeChange"
              >
                <el-option label="用户名" value="username" />
                <el-option label="手机号" value="phone" />
                <el-option label="邮箱" value="email" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="form.remember">记住我</el-checkbox>
          <el-link type="primary" @click="handleForgotPassword">
            忘记密码？
          </el-link>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="isLoggingIn"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="register-link">
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </div>

        <el-divider>其他登录方式</el-divider>

        <div class="social-login">
          <el-button
            class="social-button"
            @click="handleSocialLogin('wechat')"
          >
            <el-icon><Wechat /></el-icon>
            微信登录
          </el-button>
          <el-button
            class="social-button"
            @click="handleSocialLogin('qq')"
          >
            <el-icon><ChatDotRound /></el-icon>
            QQ登录
          </el-button>
          <el-button
            class="social-button"
            @click="handleSocialLogin('weibo')"
          >
            <el-icon><Share /></el-icon>
            微博登录
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="找回密码"
      width="400px"
    >
      <el-form
        ref="forgotFormRef"
        :model="forgotForm"
        :rules="forgotRules"
        label-width="0"
      >
        <el-form-item prop="account">
          <el-input
            v-model="forgotForm.account"
            :placeholder="请输入手机号/邮箱"
          />
        </el-form-item>

        <el-form-item prop="code">
          <div class="verify-code">
            <el-input
              v-model="forgotForm.code"
              placeholder="请输入验证码"
            />
            <el-button
              type="primary"
              :disabled="isCodeSending"
              @click="handleSendCode"
            >
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="newPassword">
          <el-input
            v-model="forgotForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="forgotForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="forgotPasswordVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="isResetting"
            @click="handleResetPassword"
          >
            重置密码
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Wechat,
  ChatDotRound,
  Share
} from '@element-plus/icons-vue'

const router = useRouter()

// 登录类型
const loginType = ref('username')
const accountPlaceholder = computed(() => {
  switch (loginType.value) {
    case 'username':
      return '请输入用户名'
    case 'phone':
      return '请输入手机号'
    case 'email':
      return '请输入邮箱'
    default:
      return '请输入账号'
  }
})

// 登录表单
const formRef = ref(null)
const form = ref({
  account: '',
  password: '',
  remember: false
})

// 表单验证规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (loginType.value === 'phone') {
          if (!/^1[3-9]\d{9}$/.test(value)) {
            callback(new Error('请输入正确的手机号'))
          }
        } else if (loginType.value === 'email') {
          if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
            callback(new Error('请输入正确的邮箱地址'))
          }
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 登录状态
const isLoggingIn = ref(false)

// 忘记密码相关
const forgotPasswordVisible = ref(false)
const forgotFormRef = ref(null)
const forgotForm = ref({
  account: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const forgotRules = {
  account: [
    { required: true, message: '请输入手机号/邮箱', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== forgotForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 验证码相关
const isCodeSending = ref(false)
const countdown = ref(0)
const codeButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}秒后重试` : '获取验证码'
})

// 重置密码状态
const isResetting = ref(false)

// 切换登录类型
const handleLoginTypeChange = () => {
  form.value.account = ''
  formRef.value?.clearValidate('account')
}

// 登录
const handleLogin = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    isLoggingIn.value = true
    // TODO: 调用登录 API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    isLoggingIn.value = false
  }
}

// 忘记密码
const handleForgotPassword = () => {
  forgotForm.value = {
    account: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  }
  forgotPasswordVisible.value = true
}

// 发送验证码
const handleSendCode = async () => {
  if (isCodeSending.value) return

  try {
    // 验证账号
    await forgotFormRef.value.validateField('account')
    
    isCodeSending.value = true
    countdown.value = 60
    
    // TODO: 调用发送验证码 API
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isCodeSending.value = false
      }
    }, 1000)
  } catch (error) {
    console.error('验证失败:', error)
  }
}

// 重置密码
const handleResetPassword = async () => {
  if (!forgotFormRef.value) return
  
  try {
    await forgotFormRef.value.validate()
    
    isResetting.value = true
    // TODO: 调用重置密码 API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    ElMessage.success('密码重置成功')
    forgotPasswordVisible.value = false
  } catch (error) {
    console.error('重置失败:', error)
  } finally {
    isResetting.value = false
  }
}

// 社交登录
const handleSocialLogin = (type) => {
  // TODO: 实现社交登录
  ElMessage.info(`暂不支持${type}登录`)
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-bg-color-page);
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--el-text-color-primary);
}

.subtitle {
  margin: 10px 0 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.login-form {
  margin-top: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.register-link a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.social-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.verify-code {
  display: flex;
  gap: 10px;
}

.verify-code .el-input {
  flex: 1;
}
</style> 